package net.tensor.skynet.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.icu.text.SimpleDateFormat
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import net.tensor.skynet.service.UserService
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.InputStream
import java.security.KeyStore
import java.security.SecureRandom
import java.util.*
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager

class BaseUtils {

    @SuppressLint("SimpleDateFormat")
    fun getNow(): String {
        return if (android.os.Build.VERSION.SDK_INT >= 24) {
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Date())
        } else {
            var tms = Calendar.getInstance()
            tms.get(Calendar.YEAR).toString() + "-" + tms.get(Calendar.MONTH)
                .toString() + "-" + tms.get(Calendar.DAY_OF_MONTH).toString() + " " + tms.get(
                Calendar.HOUR_OF_DAY
            ).toString() + ":" + tms.get(Calendar.MINUTE)
                .toString() + ":" + tms.get(Calendar.SECOND)
                .toString() + "." + tms.get(Calendar.MILLISECOND).toString()
        }
    }

    fun getGson(): Gson? {
        return GsonBuilder()
            .setLenient()
            .create()
    }

    fun getInputStream(activity: Activity, resourceId: Int): InputStream {
        return activity.resources.openRawResource(resourceId)
    }

    fun getTrustManager(stream: InputStream): X509TrustManager? {
        val okHttpClientManager = OkHttpClientManager()
        val trustManager = okHttpClientManager.trustManagerForCertificates(stream)

        val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
        val trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)
        return trustManager
    }

    fun getSSLContext(trustManager: X509TrustManager): SSLContext? {
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(
            null, arrayOf<TrustManager>(trustManager),
            SecureRandom()
        )
        return sslContext
    }

    fun getOkHttpClient(trustManager: X509TrustManager, sslContext: SSLContext): OkHttpClient {
        return OkHttpClient.Builder()
            .sslSocketFactory(sslContext.socketFactory, trustManager)
            .build()
    }

    fun getRetrofit(
        okHttpClient: OkHttpClient,
        host: String,
        gson: Gson
    ): UserService {
        return Retrofit.Builder()
            .baseUrl(host)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(UserService::class.java)
    }
}